<template>
  <scroll-view
    scroll-y="ture"
    style="height: 100vh"
    class="order_detail_content"
  >
    <view v-if="showType === 'receive'">
      <view class="goods_info">
        <view class="share_title"> - 你的礼物 -</view>
        <image class="card_image" :src="orderInfo.giftCardFront" />
        <view class="show_title">
          {{ orderInfo.giftCardWord }}
          <image class="line_1" :src="oss2('funCard/card_line.png')" />
          <image class="line_2" :src="oss2('funCard/card_line.png')" />
        </view>
        <view class="share_text">奥利奥乳酪蛋糕</view>
        <image class="goods_image" :src="goodsImage" />
        <view class="goods_sku">
          <view class="name">乳酪蛋糕</view>
          <view class="sku">{{ skuInfo }}</view>
          <view class="quantity">{{ skuQuantity }}份</view>
        </view>
      </view>

      <view class="order_info">
        <view class="address_info">
          <image class="line" :src="oss2('order/line.png')" />
          <view
            class="text"
            v-if="orderInfo.orderStatus === 2 || orderInfo.orderStatus === 3"
            @click="toRecord()"
          >
            该订单已拆分成1个包裹发出，已全部发货，点击可查看详情
          </view>
          <view class="address">
            <label
              >{{ orderInfo.receiverName }} {{ orderInfo.receiverPhone }}
            </label>
            <label
              >{{ orderInfo.receiverProvince }} {{ orderInfo.receiverCity
              }}{{ orderInfo.receiverRegion
              }}{{ orderInfo.receiverDetailAddress }}
            </label>
          </view>
        </view>

        <view class="order_detail">
          <label class="title">订单信息</label>
          <label>订单编号：{{ orderInfo.id }}</label>
        </view>
      </view>
    </view>

    <view v-else>
      <view class="receive_info">
        <view class="address_info">
          <image class="line" :src="oss2('order/line.png')" />
          <view class="card">
            <image :src="orderInfo.giftCardFront" />
            {{ orderInfo.giftCardTheme }}
          </view>
          <view class="wish">{{ orderInfo.giftCardWord }}</view>
        </view>

        <view class="detail_info">
          <view class="goods">
            <image class="goods_image" :src="goodsImage" />
            <view class="goods_name">{{ goodsName }}</view>
            <view class="goods_price">
              <label>￥{{ orderInfo.finalAmount || 0 }}</label>
              <label class="count">x{{ skuQuantity }}</label>
            </view>
          </view>

          <view class="pay-handle">
            <view
              @click="toRefund(orderInfo)"
              v-if="orderInfo.orderStatus === 3 || orderInfo.orderStatus === 7"
            >
              申请退款
              <!-- {{ filterRefundStatusText(orderInfo.refundStatus) }} -->
            </view>
            <button
              @click="toKefu"
              class="rule_kefu"
              open-type="contact"
              v-if="orderInfo.orderStatus === 1 || orderInfo.orderStatus === 2"
            >
              <view class="service">发起售后</view>
            </button>
          </view>

          <view class="pay-info__line">
            <label>商品金额：</label>
            <view class="price">
              <view class="master">{{ orderInfo.totalAmount }}</view>
            </view>
          </view>
          <view class="pay-info__line">
            <label>运费：</label>
            <view>
              <view class="master">{{
                orderInfo.freightAmount === 0
                  ? "包邮"
                  : "¥" + orderInfo.freightAmount
              }}</view>
            </view>
          </view>
          <view class="pay-info__line">
            <label>商品优惠：</label>
            <view class="price">
              <view class="master">{{ orderInfo.couponAmount }}</view>
            </view>
          </view>
          <view class="pay-info__line" style="margin-bottom: 5px">
            <label>实付金额（含运费）：</label>
            <view class="price text-primary">
              <view class="master">{{
                cal.jia(orderInfo.finalAmount, orderInfo.freightAmount)
              }}</view>
            </view>
          </view>
        </view>

        <view class="order_detail">
          <label class="title">订单信息</label>
          <label>订单编号：{{ orderInfo.id }}</label>
          <label>下单时间：{{ orderInfo.createTime }}</label>
          <label>付款时间：{{ orderInfo.payTime }}</label>
        </view>
      </view>

      <view
        class="order-handle"
        v-if="orderInfo.orderStatus !== 1 && orderInfo.orderStatus !== 7"
      >
        <button
          @click="
            linkTo('/personalPages/order/logisticsDetail?id=' + orderInfo.id)
          "
          v-if="orderInfo.orderStatus === 2"
        >
          查看物流
        </button>
        <button
          class="primary"
          v-if="orderInfo.orderStatus === 0 || orderInfo.orderStatus === 6"
          @click.stop="toPurchase(orderInfo)"
        >
          立即付款
        </button>
        <button
          v-if="orderInfo.orderStatus === 0 || orderInfo.orderStatus === 6"
          @click.stop="toCancel(orderInfo)"
        >
          取消订单
        </button>
        <button
          open-type="share"
          v-if="orderInfo.orderStatus === 7"
          @click="toShare"
        >
          <view class="pay">立即分享</view>
        </button>
        <button
          class="delete"
          v-if="
            orderInfo.orderStatus === 3 ||
            orderInfo.orderStatus === 4 ||
            orderInfo.orderStatus === 5
          "
          @click.stop="toDelete(orderInfo)"
        >
          删除订单
        </button>
      </view>
    </view>
  </scroll-view>


</template>

<script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, debounce, message } from "@/utils/utils";
import { cal } from "@/utils/cal";
import { wxOrderPurchase } from "@/services/mall";
import {
  GetOrderInfo,
  Subscribe,
  Cancel,
  Refund,
  Delete,
} from "@/services/giftcard.js";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const showType = ref("send");
const orderId = ref(0);
const orderInfo = ref({});
const goodsImage = ref("");
const goodsName = ref("");
const skuInfo = ref("");
const skuQuantity = ref(0);
const linkTo = (url) => uni.navigateTo({ url });

onLoad((option) => {
  uni.hideShareMenu();

  if (option.type) {
    showType.value = option.type;
  }
  orderId.value = option.orderId;
  getOrderInfo();
});
onShow(() => {
  // 用户进入时间
  enterTime = new Date();
});
onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    showType.value === "send" ? "fc_giver_orders" : "fc_recipient_orders",
    "view",
    showType.value === "send" ? "fc_details_page_1" : "fc_details_page_2",
    stayTime
  );
});
onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    showType.value === "send" ? "fc_giver_orders" : "fc_recipient_orders",
    "view",
    showType.value === "send" ? "fc_details_page_1" : "fc_details_page_2",
    stayTime
  );
});

const getOrderInfo = async () => {
  const { data } = await GetOrderInfo(orderId.value);
  orderInfo.value = data;
  goodsImage.value = data.items[0].productImageUrl;
  goodsName.value = data.items[0].productName;
  skuInfo.value = data.items[0].productSkuSpData[0].value;
  skuQuantity.value = data.items[0].productSkuQuantity;
};

const toPurchase = debounce(
  async (item) => {
    getApp().emdlz2(
      "track",
      "event",
      "fc_giver_orders",
      "click",
      "fc_pay_now_2",
      ""
    );

    const res = await wxOrderPurchase({
      id: item.id,
      appId: process.env.WXAPPID,
    });
    console.log("------------------支付", res.data);
    if (res?.code === 200) {
      uni.requestPayment({
        provider: "wxpay", //支付类型-固定值
        timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
        nonceStr: res.data.nonceStr, // 随机字符串
        package: res.data.package, // 固定值
        signType: res.data.signType, //固定值
        paySign: res.data.paySign, //签名
        success: async function (res) {
          console.log("success:" + JSON.stringify(res));
          getApp()
            .sr()
            .track("custom_order", {
              order: {
                order_id: item.id,
                order_time: Date.now(),
                order_status: "payed",
              },
              sub_orders: [
                {
                  sub_order_id: item.id,
                  order_amt: item.finalAmount,
                  pay_amt: item.finalAmount,
                },
              ],
              // more...
            });

          message("支付成功", 1000);
          // 订阅
          uni.requestSubscribeMessage({
            tmplIds: [
              process.env.FUNCARDDELIVERYNOTICE,
              process.env.FUNCARDSIGNNOTICE,
              process.env.FUNCARDREFUNDSUCCESSNOTICE,
            ],
            success: async (res2) => {
              await Subscribe({
                appId: process.env.WXAPPID,
                orderId: orderId.value,
                scene: [
                  "GIFTCARD_STATE_CHANGE",
                  "ORDER_DELIVERY",
                  "REFUND_SUCCEED",
                ],
              });
            },
            fail: function (err) {
              console.log(err);
            },
          });

          uni.redirectTo({
            url: "/funCard/share?orderId=" + item.id + "&type=send",
          });
        },
        fail: function (err) {
          console.log("fail:" + JSON.stringify(err));
          getApp()
            .sr()
            .track("custom_order", {
              order: {
                order_id: item.id,
                order_time: Date.now(),
                order_status: "cancel_pay",
              },
              sub_orders: [
                {
                  sub_order_id: item.id,
                  order_amt: item.finalAmount,
                  pay_amt: item.finalAmount,
                },
              ],
              // more...
            });

          uni.showModal({
            title: "确定取消支付吗？",
            content: "120分钟内未付款，订单将自动关闭，请尽快付款哦！",
            cancelText: "稍后付款",
            confirmText: "继续付款",
            success: function (res) {
              if (res.confirm) {
                console.log("用户点击确定");
                uni.redirectTo({
                  url: "/funCard/order",
                });
              } else if (res.cancel) {
                console.log("用户点击取消");
                message("取消支付");
              }
            },
          });
        },
      });
    } else {
      message(res.message);
    }
  },
  500,
  false
);
const toCancel = debounce(
  async (item) => {
    getApp().emdlz2(
      "track",
      "event",
      "fc_giver_orders",
      "click",
      "fc_cancel_order_2",
      ""
    );

    const res = await Cancel({ id: item.id });
    if (res?.code === 200) {
      getApp()
        .sr()
        .track("custom_order", {
          order: {
            order_id: item.id,
            order_time: Date.now(),
            order_status: "cancel_give_order",
          },
          sub_orders: [
            {
              sub_order_id: item.id,
              order_amt: item.totalAmount,
              pay_amt: item.finalAmount,
            },
          ],
        });
      await message("取消成功", 2000);
      getOrderInfo();
    } else {
      message(res.message);
    }
  },
  500,
  false
);
const toRefund = async (item) => {
  // 订阅
  uni.requestSubscribeMessage({
    tmplIds: [process.env.FUNCARDREFUNDSUCCESSNOTICE],
    success: async (res2) => {
      await Subscribe({
        appId: process.env.WXAPPID,
        orderId: item.id,
        scene: ["REFUND_ACCEPT"],
      });
    },
    fail: function (err) {
      console.log(err);
    },
  });

  const res = await Refund({
    orderId: item.id,
    refundReason: "",
    orderItemIds: [],
    refundScope: 0,
    description: "",
  });
  if (res?.code === 200) {
    message("退款成功");
    getOrderInfo();
  } else {
    message(res.message);
  }
  getApp().emdlz2(
    "track",
    "event",
    "fc_giver_orders",
    "click",
    "fc_refunds_2",
    ""
  );
};
const toDelete = debounce(
  (item) => {
    getApp().emdlz2(
      "track",
      "event",
      "fc_giver_orders",
      "click",
      "fc_delete_order_2",
      ""
    );
    uni.showModal({
      content: "确定是否删除此订单？",
      success: async function (res) {
        if (res.confirm) {
          const res = await Delete(item.id);
          if (res?.code === 200) {
            await message("删除成功", 2000);
            uni.redirectTo({
              url: "/funCard/order",
            });
          }
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  500,
  false
);
const toKefu = () => {
  getApp().emdlz2(
    "track",
    "event",
    "fc_giver_orders",
    "click",
    "fc_after_sales_2",
    ""
  );
};
const toShare = () => {
  getApp().emdlz2(
    "track",
    "event",
    "fc_giver_orders",
    "click",
    "fc_share_order_2",
    ""
  );
};

onShareAppMessage((e) => {
  const shareObj = {
    title: "送你一份奥利奥玩心小礼物，快来领取！", // 默认是小程序的名称(可以写slogan等)
    path: "/funCard/share?orderId=" + orderInfo.value.id, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("funCard/gift_wx.png"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});

const toRecord = () => {
  getApp().emdlz2(
    "track",
    "event",
    "fc_recipient_orders",
    "click",
    "fc_view_logistics",
    ""
  );

  uni.navigateTo({
    url: "/personalPages/order/logisticsDetail?id=" + orderInfo.value.id,
  });
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";
.order_detail_content {
  width: 375px;
  background-color: #f7f7f7;
  text-align: center;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: #000000;
  .goods_info {
    height: 540px;
    background-color: #fff;
    box-sizing: border-box;
    padding-top: 25px;
    .share_title {
      height: 20px;
      line-height: 20px;
      font-size: 20px;
      font-weight: bold;
    }
    .card_image {
      width: 235px;
      height: 144px;
      border-radius: 8px;
      margin-top: 17px;
    }
    .show_title {
      position: relative;
      width: 236px;
      height: 62px;
      line-height: 36px;
      font-size: 15px;
      color: #000000;
      margin: 0 auto;
      image {
        position: absolute;
        left: 0;
        width: 236px;
        height: 1px;
      }
      .line_1 {
        top: 31px;
      }
      .line_2 {
        bottom: 0;
      }
    }
    .share_text {
      font-size: 12px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #0044c9;
      margin-top: 19px;
    }
    .goods_image {
      width: 141px;
      height: 141px;
      border-radius: 5px;
      margin-top: 15px;
    }
    .goods_sku {
      height: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      margin-top: 16px;
      margin-bottom: 53px;
      .name {
        padding-right: 12px;
        border-right: 2px solid #376799;
      }
      .sku {
        padding: 0 12px;
        border-right: 2px solid #376799;
      }
      .quantity {
        padding-left: 12px;
      }
    }
  }

  .address_info {
    position: relative;
    width: 351px;
    height: 156px;
    background-color: #ffffff;
    border-radius: 2px;
    margin-bottom: 6px;
    box-sizing: border-box;
    padding: 28px 8px 10px;
    .line {
      position: absolute;
      top: 0;
      left: 0;
      width: 351px;
      height: 10px;
    }
  }
  .order_detail {
    width: 351px;
    height: 100px;
    background-color: #ffffff;
    border-radius: 2px;
    box-sizing: border-box;
    padding: 12px 8px;
    .title {
      color: #353535;
    }
    label {
      display: block;
      height: 14px;
      line-height: 14px;
      font-size: 14px;
      font-weight: 400;
      color: #b8b8b8;
      margin-bottom: 7px;
    }
    label:last-child {
      margin-bottom: 0;
    }
  }
  .order_info {
    height: 286px;
    box-sizing: border-box;
    padding: 12px;
    text-align: left;

    .address_info {
      .text {
        width: 308px;
        height: 33px;
        font-size: 12px;
        font-weight: 400;
        color: #0058c6;
        line-height: 18px;
        margin-bottom: 25px;
      }
      .address {
        width: 335px;
        height: 62px;
        background-color: #f8f8f8;
        border-radius: 4px;
        box-sizing: border-box;
        padding: 14px 8px;
        label {
          display: block;
          height: 12px;
          line-height: 12px;
          font-size: 12px;
          font-family: Adobe Heiti Std;
          font-weight: normal;
          color: #7d7d7d;
        }
        label:first-child {
          margin-bottom: 10px;
        }
      }
    }
  }

  .receive_info {
    height: calc(100vh - 64px);
    min-height: 618px;
    box-sizing: border-box;
    padding: 16px 12px;
    font-size: 14px;
    color: #000000;
    font-weight: 500;
    text-align: left;

    .address_info .card {
      height: 43px;
      font-weight: bold;
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      image {
        width: 70px;
        height: 43px;
        border-radius: 4px;
        margin-right: 15px;
      }
    }
    .address_info .wish {
      width: 327px;
      height: 47px;
      line-height: 24px;
      font-size: 15px;
    }
    .detail_info {
      width: 351px;
      height: 240px;
      background-color: #ffffff;
      border-radius: 2px;
      box-sizing: border-box;
      padding: 12px 8px;
      margin: 13px 0;
      .goods {
        width: 100%;
        height: 75px;
        display: flex;
        color: #353535;
        font-size: 14px;
        text-align: right;
        image {
          width: 75px;
          height: 75px;
          border-radius: 5px;
        }
        .goods_name {
          flex: 1;
          text-align: left;
          line-height: 18px;
          font-weight: 500;
          padding: 0 12px;
          box-sizing: border-box;
        }
        label {
          display: block;
        }
        .count {
          font-size: 12px;
          color: #818181;
          line-height: 1;
          margin-top: 5px;
        }
      }

      .pay-handle {
        padding-top: 2px;
        padding-bottom: 13px;
        display: flex;
        justify-content: flex-end;

        view {
          width: 60px;
          height: 24px;
          line-height: 24px;
          text-align: center;
          background: #ffffff;
          border: 1px solid #2c2c2c;
          border-radius: 12px;
          font-size: 12px;
          color: #1b1b1b;
        }
        .rule_kefu {
          margin-left: 0;
          margin-right: 0;
          padding: 0;
          background-color: transparent;
          &::after {
            border: none;
          }
        }
      }
      .pay-info__line {
        display: flex;
        align-items: center;
        justify-content: space-between;
        line-height: 1;
        margin-bottom: 9px;
        font-size: 14px;
        color: #353535;

        label {
          font-size: 14px;
        }
      }
    }
  }

  .order-handle {
    width: 100%;
    height: 64px;
    display: flex;
    justify-content: flex-end;
    background-color: white;
    z-index: 99;
    position: sticky;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    padding: 16px 12px 0 12px;

    button {
      margin: 0;
      margin-left: 12px;
      width: 80px;
      height: 32px;
      line-height: 31px;
      background: #ffffff;
      border: 1px solid #404040;
      border-radius: 32px;
      font-size: 14px;
      color: #363636;
      padding: 0;
      &.delete {
        color: @label-color;
        border-color: @label-color;
      }
      &.primary {
        color: @primary-color;
        border-color: @primary-color;
      }

      &::after {
        border: none;
      }
    }
  }
}
</style>
